package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/jinzhu/gorm"
	"strconv"
	"witer/models"
)

type MainController struct {
	beego.Controller
}

type Res struct {
	Cre  int
	Msg  string
	Data interface{}
}

// 查询
func (c *MainController) Show() {
	id := c.GetString("id")

	var writer models.Author
	get := models.RedisDB.Get("witer" + id) //读取数据 写入时

	//判断数据是否在缓存中
	if get.Val() != "" { //代表有数据
		json.Unmarshal([]byte(get.Val()), &writer) //读取缓存中的数据
	} else { //如果缓存中没有数据
		models.DB.Debug().Where("id = ? ", id).Order("id desc").Find(&writer) //执行原生sql语句

		//然后把查询到的数据写入到缓存数据中
		marshal, _ := json.Marshal(writer) //转成json格式

		models.RedisDB.Set("witer"+id, marshal, 0) //写入数据

	}

	//输出json格式
	c.Data["json"] = Res{200, "查询详情成功", writer}
	c.ServeJSON(true)

}

// 添加
func (c *MainController) Add() {
	HeadImg := c.GetString("HeadImg")       //需要添加的数据
	AuthorName := c.GetString("AuthorName") //需要添加的数据

	//写入
	writer := models.Author{
		Model:      gorm.Model{},
		HeadImg:    HeadImg,
		AuthorName: AuthorName,
	}
	//完成写入
	models.DB.Create(&writer)

	//获取id 结构体的id
	id := strconv.Itoa(int(writer.ID)) //转字符串
	marshal, _ := json.Marshal(writer) //将写入的数据转json

	models.RedisDB.Set("witer"+id, marshal, 0) //写入缓存数据

	c.Data["json"] = Res{200, "新增成功", writer}
	c.ServeJSON(true)
}

// 删除
func (c *MainController) Del() {
	id, _ := c.GetInt("id")
	writer := models.Author{
		Model: gorm.Model{ID: uint(id)},
	}
	models.DB.Debug().Delete(&writer)

	itoa := strconv.Itoa(id)

	models.RedisDB.Del("witer" + itoa)

	c.Data["json"] = Res{200, "删除成功", nil}
	c.ServeJSON(true)

}

func (c *MainController) List() {
	//redis有记录次数的功能
	models.RedisDB.Incr("number")

	var writer []models.Author
	get := models.RedisDB.Get("writerlist")
	if get.Val() != "" {
		json.Unmarshal([]byte(get.Val()), writer)
	} else {
		models.DB.Debug().Find(&writer)

		//想要写人缓存数据里面必须要转成json才能存入成功
		marshal, _ := json.Marshal(writer)

		models.RedisDB.Set("writerlist", marshal, 0)
	}

	c.Data["json"] = Res{200, "获取列表成功", writer}
	c.ServeJSON(true)

}
